<?php
/**
 * Created by PhpStorm.
 * User: C。
 * Date: 2019/8/13
 * Time: 9:04
 */
namespace app\home\controller;

use app\common\model\ChatWechat as ChatWechatModel;
use app\common\model\Config as ConfigModel;
use think\Controller;
use think\Db;
/**
 * Cate 课程
 * Class Cate
 * @package app\home\controller
 */
class Chat extends Controller
{
    /**
     * [getIndex  获取课程]
     * @param $of 1早课 2晚课
     * @return json
     * @author [C。]
     */
    public function login()
    {
        $param = input('param.');
        $model = new ConfigModel;
        $cwmodel = new ChatWechatModel;
        $appid = $model->findData('zh_appid','cname','cvalue');
        $secret = $model->findData('zh_secret','cname','cvalue');
        $code = $param['code'];
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid['cvalue'] . '&secret=' . $secret['cvalue'] . '&code=' . $code . '&grant_type=authorization_code';
        $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据，推荐使用curl
        $json = json_decode($info);//对json数据解码
        $arr = get_object_vars($json);
        if (empty($arr['access_token'])) {
            return admin_json('-1', $arr);
        }
        $access_token = $arr['access_token'];
        $openid = $arr['openid'];
        $user_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user_info = file_get_contents($user_url);//发送HTTPs请求并获取返回的数据，推荐使用curl
        $user_json = json_decode($user_info);//对json数据解码
        $user_arr = get_object_vars($user_json);

        $wechat = $cwmodel->findData($user_arr['openid'],'openid');
        if(empty($wechat)){
            $cwmodel->addData($user_arr);
        }

        return admin_json('1', '获取成功',$user_arr);
    }
}